<?php


namespace App\Services\Api;


use App\Constants\BaseConstants;
use App\Constants\ErrorMsgConstants;
use App\Exceptions\ServiceException;
use App\Models\AppUser;
use App\Models\UserTask;
use App\Services\GravatarService;
use App\Services\VerificationCodeService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class UserAppService
{
    private $logger;
    private $wechatService;
    private $gravatarService;

    public function __construct(
        WechatService $wechatService,
        GravatarService $gravatarService
    )
    {
        $this->logger = customerLoggerHandle('UserAppService');
        $this->wechatService = $wechatService;
        $this->gravatarService = $gravatarService;
    }

    /**
     * 微信登录
     * @param $jsCode
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function login($jsCode)
    {
        $appId = env('WECHAT_MINI_PROGRAM_APP_ID');
        $secret = env('WECHAT_MINI_PROGRAM_SECRET');
        $authData = $this->wechatService->getOpenIdForCode($jsCode, $appId, $secret);
        if (!isset($authData['openid'])) {
            throw new ServiceException(
                ErrorMsgConstants::DEFAULT_ERROR,
                '登录失败'
            );
        }

        $userData = $this->getUser($authData['openid']);
        $userData['sessionKey'] = $authData['session_key'];

        return $userData;
    }



    /**
     * 获取用户或新建 并返回jwt token
     * @param $openId
     * @return array
     */
    public function getUser($openId)
    {
        /**
         * @property string $id
         * @property string $name 用户名
         * @property string $password 密码
         * @property string $open_id 微信openId
         * @property string|null $phone_number 手机号
         * @property string|null $avatar 头像
         * @property string|null $id_card_no 身份证号
         * @property int $gender 性别:0女,1男,2未知
         * @property int $point 会员积分
         */

        /** @var AppUser $appUserModel */
        $appUserModel = AppUser::whereOpenId($openId)->first();
        if (!$appUserModel) {
            $appUserModel = new AppUser();
            $appUserModel->name = "用户" . time();
            $appUserModel->password = password_hash(md5(time()), PASSWORD_BCRYPT);
            $appUserModel->open_id = $openId;
            $appUserModel->save();
        }

        $appUserModel->refresh();

        $token = $this->getAppUserJwtToken($appUserModel);

        return [
            'token' => $token,
            'tokenOutTime' => time() + (50 * 60),
        ];
    }

    /**
     * @param $appUser
     * @return string
     */
    private function getAppUserJwtToken(AppUser $appUser)
    {
        $this->logger->info("获得用户信息", [
            $appUser->open_id,
            $appUser->name,
        ]);

        $token = auth('api')->login($appUser);

        return "Bearer " . $token;
    }

    /**
     * @param $phone
     * @return bool
     * @throws \Exception
     */
    public function loginSendCode($phone)
    {
        try {
            $cacheKey = "LOGIN_SEND_CODE_" . $phone;
            if (Cache::has($cacheKey)) {
                throw new ServiceException(ErrorMsgConstants::DEFAULT_ERROR, "短信发送过于频繁,请在2分钟以后重试!");
            }
//            $appUser = getAppUserModelForName($userName);
            /**
             * 发送短信验证码
             * @var VerificationCodeService $verificationCodeService
             */
            $verificationCodeService = app(VerificationCodeService::class);
            $vc = $verificationCodeService->sendVerificationCode($phone);

            Cache::put($cacheKey, $vc, 2);
            return $vc;
        } catch (\Exception $exception) {
            $this->logger->debug("异常", getExceptionMainInfo($exception));
            throw $exception;
        }
    }

    /**
     * 存储手机号
     * @param $phone
     * @param $local
     * @return bool
     */
    public function savePhone($phone,$local)
    {
        $appUser = getAppUser();
        $appUser->phone_number = $phone;
        $appUser->point = 750;
        $appUser->location = $local;
        $appUser->update();
        $data['point'] = $appUser->point;
        $data['time'] = date('Y-m-d',time());
        return $data;
    }



    /**
     * 更新用户信息
     * @param Request $request
     * @return bool
     */
    public function update(Request $request)
    {
        $appUser = getAppUser();
        $appUserModel  = AppUser::whereId($appUser->id)->first();
        $name          = $request->input('name');
        $gender        = $request->input('sex');
        $idCardNo      = $request->input('id_card_no');
        $birthday      = $request->input('birthday');
        $area          = $request->input('area');
        $task          = $request->input('task');
        if (!$appUserModel) {
            throw new ServiceException(null, '用户信息异常!');
        }
        $taskModel = UserTask::whereUserId($appUser->id)->whereTaskId($task)->first();

        if (!is_null($name)) {$appUserModel->name = $name;}
        if (!is_null($gender)) {$appUserModel->gender = $gender;}
        if (!is_null($idCardNo)) {$appUserModel->id_card_no = $idCardNo;}
        if (!is_null($birthday)) {$appUserModel->birthday = $birthday;}
        if (!is_null($area)) {$appUserModel->area = $area;}
        if (empty($taskModel)){
            $taskModel->user_id = $appUser->id;
            $taskModel->task_id = $task;
            $taskModel->save();
            $appUserModel->increment('point',5);
        }
        return $appUserModel->update();
    }

    /**
     * 更新完善工作信息
     * @param Request $request
     * @return bool|int
     */
    public function updateWorkerInfo(Request $request)
    {
        $appUser = getAppUser();
        $appUserModel  = AppUser::whereId($appUser->id)->first();
        $company       = $request->input('company');
        $workerAddress = $request->input('worker_address');
        $workerTime = $request->input('worker_time');
        $workerLevel   = $request->input('worker_level');
        $income        = $request->input('income');
        $task          = $request->input('task');
        if (!$appUserModel) {
            throw new ServiceException(null, '用户信息异常!');
        }
        $taskModel = UserTask::whereUserId($appUser->id)->whereTaskId($task)->first();
        if (!is_null($company)) {$appUserModel->company = $company;}
        if (!is_null($workerAddress)) {$appUserModel->worker_address = $workerAddress;}
        if (!is_null($workerLevel)) {$appUserModel->worker_level = $workerLevel;}
        if (!is_null($income)) {$appUserModel->income = $income;}
        if (!is_null($workerTime)) {$appUserModel->worker_time = $workerTime;}
        if (empty($taskModel)){
            $taskModel->user_id = $appUser->id;
            $taskModel->task_id = $task;
            $taskModel->save();
            $appUserModel->increment('point',5);
        }
        return $appUserModel->update();
    }

    /**
     * 更新完善车辆信息
     * @param Request $request
     * @return bool|int
     */
    public function updateCarInfo(Request $request)
    {
        $appUser = getAppUser();
        $appUserModel  = AppUser::whereId($appUser->id)->first();
        $carA          = $request->input('car_a');
        $carB          = $request->input('car_b');
        $task          = $request->input('task');
        if (!$appUserModel) {
            throw new ServiceException(null, '用户信息异常!');
        }
        $taskModel = UserTask::whereUserId($appUser->id)->whereTaskId($task)->first();
        if (!is_null($carA)) {$appUserModel->car_a = $carA;}
        if (!is_null($carB)) {$appUserModel->car_b = $carB;}
        if (empty($taskModel)){
            $taskModel->user_id = $appUser->id;
            $taskModel->task_id = $task;
            $taskModel->save();
            $appUserModel->increment('point',5);
        }
        return $appUserModel->update();
    }

    /**
     * 更新房产信息
     * @param Request $request
     * @return bool|int
     */
    public function updateHouseInfo(Request $request)
    {
        $appUser = getAppUser();
        $appUserModel  = AppUser::whereId($appUser->id)->first();
        $house         = $request->input('house');
        $task          = $request->input('task');
        if (!$appUserModel) {
            throw new ServiceException(null, '用户信息异常!');
        }
        $taskModel = UserTask::whereUserId($appUser->id)->whereTaskId($task)->first();
        if (!is_null($house)) {$appUserModel->house = $house;}
        if (empty($taskModel)){
            $taskModel->user_id = $appUser->id;
            $taskModel->task_id = $task;
            $taskModel->save();
            $appUserModel->increment('point',5);
        }
        return $appUserModel->update();
    }

    /**
     * 更新学校信息
     * @param Request $request
     * @return bool|int
     */
    public function updateSchoolInfo(Request $request)
    {
        $appUser = getAppUser();
        $appUserModel  = AppUser::whereId($appUser->id)->first();
        $school        = $request->input('school');
        $task          = $request->input('task');
        if (!$appUserModel) {
            throw new ServiceException(null, '用户信息异常!');
        }
        $taskModel = UserTask::whereUserId($appUser->id)->whereTaskId($task)->first();
        if (!is_null($school)) {$appUserModel->school = $school;}
        if (empty($taskModel)){
            $taskModel->user_id = $appUser->id;
            $taskModel->task_id = $task;
            $taskModel->save();
            $appUserModel->increment('point',5);
        }
        return $appUserModel->update();
    }


}
